//
//  BBGlobalSearchViewController.m
//  BlockBrowser
//
//  Created by Mac on 2018/4/3.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "BBGlobalSearchViewController.h"

@interface BBGlobalSearchViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) UITextField                     *textFiled;
@property(nonatomic, strong) STButton                     *cancleButton;
@property(nonatomic, strong) NSArray                     *dataSouce;
@property(nonatomic, weak) NSURLSessionDataTask          *task;
@end

@implementation BBGlobalSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubView];
    [self addNotifacations];
    NSArray * array = [self arrayFormUserdefult];
    self.dataSouce = array;
    [self.tableView reloadData];
    
    [self configTableFooter];
    // Do any additional setup after loading the view.
}
- (void)configTableFooter{
    __weak typeof(self) weakSelf =  self;
    if (!self.textFiled.text.length && self.dataSouce.count != 0) {
        STButton * clearButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)
                                                           title:@"清除历史记录"
                                                      titleColor:SecendTextColor
                                                       titleFont:14
                                                    cornerRadius:0
                                                 backgroundColor:nil
                                                 backgroundImage:nil
                                                           image:nil];
        [clearButton setClicAction:^(UIButton *sender) {
            [weakSelf showAlertCancelAndConfirm:@"确定要删除搜索历史记录吗" andWithBlock:^(NSString *name) {
                if ([name isEqualToString:@"确认"]) {
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:searchHistoryListKey];
                    weakSelf.dataSouce = nil;
                    [weakSelf.tableView reloadData];
                    sender.hidden = YES;
                }
            }];

        }];
        clearButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        self.tableView.tableFooterView = clearButton;
    }else{
        self.tableView.tableFooterView = nil;
    }
    [self.tableView reloadData];

}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFiledDidChangeNotifacation:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)textFiledDidChangeNotifacation:(NSNotification*)notifay{
    if (notifay.object == self.textFiled) {
        [self textFiledDidChange];
    }
}
- (void)textFiledDidChange{
    if (self.textFiled.text.length) {
        [self.cancleButton setTitle:@"搜索" forState:UIControlStateNormal];
    }else{
        [self.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    if (self.textFiled.text.length) {
        [self sendKeywordRequest:self.textFiled.text];
    }
    [self configTableFooter];
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --subView
- (void)configSubView{
    UIView * serarchView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, UIScreenWidth - 20, 35)];
    serarchView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf =  self;
    
    STButton * cancleButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 60, 35)
                                                        title:@"取消"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:16
                                                 cornerRadius:0
                                              backgroundColor:[BBThemeColorManger manger].themeColor
                                              backgroundImage:nil
                                                        image:nil];
    cancleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    cancleButton.right =  serarchView.width;
    [cancleButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedButton];
    }];
    self.cancleButton = cancleButton;
    [serarchView addSubview:cancleButton];
    
    STButton * iconButton = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 60, 35)
                                                      title:nil
                                                 titleColor:nil
                                                  titleFont:0
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"网络_l"]];
    iconButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, serarchView.width - cancleButton.width, serarchView.height)];
    self.textFiled.placeholder = @"搜索或者输入网址";
    [serarchView addSubview:self.textFiled];
    self.textFiled.leftView = iconButton;
    self.textFiled.leftViewMode = UITextFieldViewModeAlways;
    self.textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textFiled.autocorrectionType =  UITextAutocorrectionTypeNo;
    self.textFiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFiled.returnKeyType = UIReturnKeySearch;
    self.textFiled.delegate = self;
    self.navigationItem.titleView = serarchView;
}
#pragma mark --Action Method
- (void)onSelctedButton{
    
    if ([self.cancleButton.currentTitle isEqualToString:@"取消"]) {
        [self.textFiled resignFirstResponder];
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self saveNewKeyWord:self.textFiled.text];
        [self sendKeywordRequest:self.textFiled.text];
        NSURL * url =   [NSURL URLWithString:self.textFiled.text];
        BOOL isUrl =  [url checkResourceIsReachableAndReturnError:nil];
        [self dismissViewControllerAnimated:NO completion:^{
            if (self.didSelctedSearch) {
                self.didSelctedSearch(self.textFiled.text);
            }
        }];
        [self saveNewKeyWord:self.textFiled.text];
        
//        if (self.dataSouce.count || isUrl) {
//            [self dismissViewControllerAnimated:NO completion:^{
//                if (self.didSelctedSearch) {
//                    self.didSelctedSearch(self.textFiled.text);
//                }
//            }];
//            [self saveNewKeyWord:self.textFiled.text];
//        }else{
//            [SVProgressHUD showErrorWithStatus:@"暂无数据"];
//        }
    }
}
#pragma mark --Private Method
- (NSArray*)arrayFormUserdefult{
    NSString * jsonStr = [[NSUserDefaults standardUserDefaults] valueForKey:searchHistoryListKey];
    NSData * data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    if (jsonStr.length) {
        NSArray * array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        return array;
    }
    return nil;
}
- (void)saveNewKeyWord:(NSString*)keyWord{
    NSMutableArray * array = [[self arrayFormUserdefult] mutableCopy];
    if (!array) {
        array = [NSMutableArray new];
    }
    if ([array containsObject:keyWord]) {
        return;
    }
    if (keyWord.length) {
        [array addObject:keyWord];
        NSString * json = array.mj_JSONString;
        [[NSUserDefaults standardUserDefaults] setValue:json forKey:searchHistoryListKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    cell.textLabel.text = [NSString stringWithFormat:@"%lu",indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.imageView.image = [UIImage imageNamed:@"放大镜33"];
    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"系统返回"]];
    cell.textLabel.text = self.dataSouce[indexPath.row];
    if (self.textFiled.text.length) {
        cell.textLabel.attributedText = [cell.textLabel.text st_convertAttributeStringWithKeyWord:self.textFiled.text attributes:@{NSForegroundColorAttributeName:TM_ThemeBackGroundColor}];
    }
    
    if (BBThemeColorManger.isBlack) {
        cell.textLabel.textColor = UIColor.whiteColor;
        cell.backgroundColor = UIColor.blackColor;
        
    }
    
    return cell;
}
#pragma mark --UITextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self onSelctedButton];
        return NO;
    }
    return YES;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * name = self.dataSouce[indexPath.row];
    self.textFiled.text = name;
    [self textFiledDidChange];
    [self dismissViewControllerAnimated:NO completion:^{
        if (self.didSelctedSearch) {
            self.didSelctedSearch(name);
        }
    }];
    [self saveNewKeyWord:name];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --NetWork Method
- (void)sendKeywordRequest:(NSString*)keyword{
    
    
    
    NSMutableDictionary * dic = [NSMutableDictionary new];
    //    search    "https://www.baidu.com/s?wd="
    //    suggestion    "http://suggestion.baidu.com/su?wd="
    NSString * finsh = [keyword stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * url = [NSString stringWithFormat:@"http://suggestion.baidu.com/su?wd=%@",finsh];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSMutableDictionary * parameters  = [NSMutableDictionary new];
    [self.task cancel];
    self.task =  [manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
        NSString *rawString=[[NSString alloc]initWithData:responseObject encoding:enc];
        NSString * first = [rawString componentsSeparatedByString:@"["].lastObject;
        NSString * finsh = [first componentsSeparatedByString:@"]"].firstObject;
        if ([finsh containsString:@","]) {
          self.dataSouce = [finsh componentsSeparatedByString:@","];
        }else{
            self.dataSouce = nil;
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
@end

